package com.caiwangdai.app.backend.utils


import android.util.Log
import com.caiwangdai.app.AppData
import com.caiwangdai.app.backend.cookie.PersistentCookieStore
import com.orhanobut.logger.Logger
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import java.io.File
import java.security.cert.CertificateException
import java.util.concurrent.TimeUnit
import javax.net.ssl.X509TrustManager


object OKHttpsUtils {
    private val DEFAULT_TIMEOUT = 20000
    private val CACHE_SIZE = 50 * 1024 * 1024;

    //Glide获取图片的问题，如果有session，url不变，图片变了。不能加载最新图片
    @Synchronized
    fun getHttpClient(needSession: Boolean = true): OkHttpClient {
        val builder = OkHttpClient.Builder()
        try {
            val trustAllCert = object : X509TrustManager {
                @Throws(CertificateException::class)
                override fun checkClientTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
                }

                @Throws(CertificateException::class)
                override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
                }

                override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
                    return arrayOf()
                }
            }
            val sslSocketFactory = SSLSocketFactoryCompat(trustAllCert)
            builder.sslSocketFactory(sslSocketFactory, trustAllCert)
                    .cache(Cache(File(AppData.context.cacheDir, "okhttp"), CACHE_SIZE.toLong()))
                    .addInterceptor(getLog())
                    .readTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.MILLISECONDS)
                    .connectTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.MILLISECONDS)
                    .writeTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.MILLISECONDS)
            if (needSession) builder.cookieJar(CookiesManager())
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
        return builder.build()
    }


    private fun getLog(): HttpLoggingInterceptor {
        val httpLoggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
            Log.d("weimu", message)
        })
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return httpLoggingInterceptor
    }

    /**
     * 保持session
     */
    private class CookiesManager : CookieJar {
        private val cookieStore = PersistentCookieStore(AppData.context)

        override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>?) {
            if (cookies != null && cookies.size > 0) {
                for (item in cookies) {
                    cookieStore.add(url, item)
                }
            }
        }

        override fun loadForRequest(url: HttpUrl): List<Cookie> {
            val cookies = cookieStore.get(url)
            return cookies
        }
    }


}
